package com.owulia.coffee.data.structure.learn.impl;

import com.owulia.coffee.data.structure.learn.LearnList;

import java.util.Arrays;

public class LearnArrayList<T> implements LearnList<T> {
    public T[] data;
    public static final int DEFlAUT_CAPT = 10;
    public int size;

    public LearnArrayList() {
        data = (T[]) new Object[DEFlAUT_CAPT];
        size = 0;
    }

    public LearnArrayList(int capt) {
        if (capt < 0) {
            throw new ArithmeticException("错误的初始长度。。。");
        }
        data = (T[]) new Object[capt];
        size = 0;
    }

    private boolean checkIndex(int index) {
        if (0 < index && index < size) {
            return true;
        }
        return false;
    }

    @Override
    public void add(T t) {
        upSize1();
        data[size] = t;
        size++;
    }

    private void upSize1() {
        if (size >= data.length) {
            upSize();
        }
    }

    private void upSize() {
        data = Arrays.copyOf(data, data.length * 2 + 2);
    }

    @Override
    public void add(int index, T t) {
        if (0 < index && index > size) {
            throw new ArithmeticException("错误的初始长度。。。");
        }
        if (index == size) {
            add(t);
        } else {
            upSize1();
            for (int i = size - 1; i >= index; i--) {
                data[i + 1] = data[i];
            }
            data[index] = t;
            size++;
        }
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public T get(int index) {
        if (!checkIndex(index)) {
            throw new ArithmeticException("错误的初始长度。。。");
        }
        return data[index];
    }

    @Override
    public T remove(int index) {
        if (!checkIndex(index)) {
            throw new ArithmeticException("错误的初始长度。。。");
        }
        T t = data[index];
        for (int i = index; i < size - 2; i++) {
            data[i] = data[i + 1];
        }
        size--;
        return t;
    }

    @Override
    public T remove(T t) {
        int index = indexOf(t);
        if (index >= 0) {
            return remove(index);
        }
        return null;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean contains(T t) {
        for (int i = 0; i < size; i++) {
            if (data[i].equals(t)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(T t) {
        for (int i = 0; i < size; i++) {
            if (data[i].equals(t)) {
                return i;
            }
        }
        return -1;
    }
}
